using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OrderingSystem.Core.Entities;
using OrderingSystem.Core.Interfaces;
using OrderingSystem.Infrastructure.Data;
using System.ComponentModel.DataAnnotations;

namespace OrderingSystem.API.Controllers
{
    [ApiController]
    [Route("config")]
    public class ConfigController : ControllerBase
    {
        private readonly ApplicationDbContext _context;
        private readonly IConfigService _configService;

        public ConfigController(ApplicationDbContext context, IConfigService configService)
        {
            _context = context;
            _configService = configService;
        }

        /// <summary>
        /// 获取所有配置
        /// </summary>
        [HttpGet("list")]
        public async Task<ActionResult<IEnumerable<Config>>> GetConfigs()
        {
            var configs = await _configService.GetConfigsAsync();
            return Ok(new { code = 0, data = configs });
        }

        /// <summary>
        /// 获取配置详情
        /// </summary>
        [HttpGet("detail/{id}")]
        public async Task<ActionResult<Config>> GetConfig(long id)
        {
            var config = await _configService.GetConfigAsync(id);
            if (config == null)
            {
                return NotFound(new { code = 1, msg = "配置不存在" });
            }

            return Ok(new { code = 0, data = config });
        }

        /// <summary>
        /// 获取配置详情 - 兼容前端info接口
        /// </summary>
        [HttpGet("info/{id}")]
        public async Task<ActionResult<Config>> GetConfigInfo(long id)
        {
            try
            {
                var config = await _configService.GetConfigAsync(id);
                if (config == null)
                {
                    return NotFound(new { code = 1, msg = "配置不存在" });
                }

                return Ok(new { code = 0, data = config });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { code = 1, msg = $"获取配置详情失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 添加配置
        /// </summary>
        [HttpPost("add")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> CreateConfig([FromBody] CreateConfigModel model)
        {
            var config = new Config
            {
                name = model.name,
                value = model.value
            };

            await _configService.CreateConfigAsync(config);
            return Ok(new { code = 0, msg = "添加成功" });
        }

        /// <summary>
        /// 更新配置
        /// </summary>
        [HttpPost("update")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> UpdateConfig([FromBody] UpdateConfigModel model)
        {
            var config = new Config
            {
                id = model.id,
                name = model.name,
                value = model.value
            };

            var result = await _configService.UpdateConfigAsync(config);
            if (result == null)
            {
                return NotFound(new { code = 1, msg = "配置不存在" });
            }

            return Ok(new { code = 0, msg = "更新成功" });
        }

        /// <summary>
        /// 删除配置
        /// </summary>
        [HttpPost("delete")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> DeleteConfig([FromQuery] long id)
        {
            try
            {
                await _configService.DeleteConfigAsync(id);
                return Ok(new { code = 0, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { code = 1, msg = $"删除配置失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 分页获取配置
        /// </summary>
        [HttpGet("page")]
        [AllowAnonymous]
        public async Task<IActionResult> GetConfigPage(
            [FromQuery] int page = 1,
            [FromQuery] int limit = 10,
            [FromQuery] string sort = "id",
            [FromQuery] string order = "desc")
        {
            try
            {
                var (items, total) = await _configService.GetConfigsPageAsync(page, limit, sort, order);

                return Ok(new
                {
                    code = 0,
                    data = new
                    {
                        total,
                        pageSize = limit,
                        totalPage = (int)Math.Ceiling((double)total / limit),
                        currPage = page,
                        list = items
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取配置分页数据时发生错误: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return StatusCode(500, new { code = 500, msg = "服务器内部错误", error = ex.Message });
            }
        }
    }

    public class CreateConfigModel
    {
        [Required]
        public string name { get; set; }
        [Required]
        public string value { get; set; }
    }

    public class UpdateConfigModel
    {
        [Required]
        public long id { get; set; }
        [Required]
        public string name { get; set; }
        [Required]
        public string value { get; set; }
    }
} 